package com.campus.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.app.mapper.UserMapper;
import com.campus.commons.entity.SocietyFor;
import com.campus.app.mapper.SocietyForMapper;
import com.campus.app.service.SocietyForsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.commons.entity.Student;
import com.campus.commons.entity.User;
import com.campus.commons.utils.*;
import com.campus.commons.utils.Error;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 学社审核 服务实现类
 * </p>
 *
 * @author Rin
 * @since 2021-01-26
 */
@Service
public class SocietyForServiceImpl extends ServiceImpl<SocietyForMapper, SocietyFor> implements SocietyForsService {

    @Autowired
    private SocietyForMapper societyForMapper;
    @Autowired
    private UserMapper userMapper;

    //<editor-fold desc="工具方法">
    private void sendMail(Integer userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("学社审核的。邮件发送失败，原因：收件人不存在");
        }
        String email = user.getEmail();
        SimpleMail.sendMail("学社审核：", "抱歉呢，本次你落选了，不要灰心下次，下次一定", email);
    }

    @Override
    public Result addSocityFor(SocietyFor societyFor) {

        return Result.result(societyForMapper.insert(societyFor));
    }

    @Override
    @Async
    public void sendMailAsync(Integer studentId, String text) {
        User user = userMapper.selectById(Student.students.get(studentId).getUserid());
        if (user == null) {
            throw new RuntimeException("学社通知的邮件发送失败，原因：收件人不存在");
        }
        String email = user.getEmail();
        SimpleMail.sendMail("学社通知：", text, email);
    }

    private Result dispose(SocietyFor byId, SocietyFor societyFor, boolean dispose) {
        Integer applystate = byId.getApplystate();
        if (applystate == -1) {
            //出错；
            return Result.error(Error.Operation_E2R, "该申请未通过，已经不能在处理了。");
        }
        if (applystate > 2) {
            return Result.error(Error.Operation_E2R, "不要越界哦！！ 这个不是你能管的。");
        }
        //更新结果
        boolean update = true;
        societyFor.setUpdatetime(new Date());
        if (dispose) {
            societyFor.setApplystate(byId.getApplystate() + 1);
            update = updateById(societyFor);
        } else {
            societyFor.setApplystate(-1);
            update = updateById(societyFor);
//                 发送邮件通知；
            sendMail(byId.getUserId());
        }
        return Result.result(update);
    }

    private QueryWrapper eqState(int start, int end) {
        QueryWrapper<SocietyFor> queryWrapper = new QueryWrapper();
        queryWrapper.between("applyState", start, end);
        return queryWrapper;
    }


    private QueryWrapper eqState(int state) {
        QueryWrapper<SocietyFor> queryWrapper = new QueryWrapper();
        queryWrapper.eq("applyState", state);
        return queryWrapper;
    }
    //</editor-fold>

    @Override
    public int delSocityFors() {
        return societyForMapper.delSocietyFors();
    }


    @Override
    public Result disposeByTch_Q(SocietyFor societyFor, boolean dispose) {
        SocietyFor byId = getById(societyFor.getId());
        if (byId.getTchopinion().trim().length() > 0) {
            return Result.error(Error.Operation_E2R, "该申请已经处理了，已经不能在处理了。");
        }
        return dispose(byId, societyFor, dispose);
    }

    @Override
    public Result disposeByLifeTch_Q(SocietyFor societyFor, boolean dispose) {
        SocietyFor byId = getById(societyFor.getId());
        if (byId.getLifetchopinion().trim().length() > 0) {
            return Result.error(Error.Operation_E2R, "该申请已经处理了，已经不能在处理了。");
        }
        return dispose(byId, societyFor, dispose);
    }

    @Override
    public Result disposeByDeTch_Q(SocietyFor societyFor, boolean dispose) {
        SocietyFor byId = getById(societyFor.getId());
        if (byId.getApplystate() != 3) {
            return Result.error(Error.Operation_E2R, " 不能对这条申请进行处理");
        }
        if (dispose) {
            societyFor.setApplystate(4);
        } else {
            societyFor.setApplystate(-1);
            sendMail(byId.getUserId());
        }
        return Result.result(updateById(societyFor));
    }

    @Override
    public Result<List<SocietyFor>> getSocietyForsByTch_Q(MyPage myPage,Integer teacherId) {
        QueryWrapper<SocietyFor> queryWrapper = eqState(0, 1);
        queryWrapper.eq("tchId", teacherId).isNull("tchOpinion");
        return Result.result(societyForMapper.selectPage(new Page<SocietyFor>(myPage.getPage(), myPage.getLimit()), queryWrapper));
    }
    @Override
    public Result<List<SocietyFor>> getSocietyForsByLifeTch_Q(MyPage myPage,Integer teacherId) {
        QueryWrapper<SocietyFor> queryWrapper = eqState(0, 1);
        queryWrapper.eq("lifeTchId", teacherId).isNull("lifeTchOpinion");
        return Result.result(societyForMapper.selectPage(new Page<SocietyFor>(myPage.getPage(), myPage.getLimit()), queryWrapper));
    }

    @Override
    public Result<List<SocietyFor>> getSocietyForsByDeTch_Q(MyPage myPage,Integer deId,Integer teacherId) {
        QueryWrapper<SocietyFor> queryWrapper = eqState(3);
        queryWrapper.eq("deId", deId);
        queryWrapper.or().eq("tchId", teacherId).or().eq("lifeTchId", teacherId);
        return Result.result(societyForMapper.selectPage(new Page<SocietyFor>(myPage.getPage(), myPage.getLimit()), queryWrapper));

    }

    @Override
    public Result<List<SocietyFor>> getExams(int page, int limit, int deId, int roleId) {
        QueryWrapper<SocietyFor> queryWrapper = new QueryWrapper<>();
        if (roleId!=2) {
            queryWrapper.eq("deId", deId);
        }
        return Result.result(societyForMapper.selectPage(new Page<SocietyFor>(page, limit), queryWrapper));
    }

    @Override
    public Result UpExamsFraction(int id, int penExam, int computerExam, int interView, int applyState) {
        SocietyFor societyFor = new SocietyFor();
        if (id == 0) {
            return Result.error(Error.Other_E1R, "id不能为空");
        }

        societyFor.setApplystate(3);
        societyFor.setId(id);
        societyFor.setPenexam(penExam);
        societyFor.setComputerexam(computerExam);
        societyFor.setInterview(interView);
        societyFor.setUpdatetime(new Date());
        societyFor.setApplystate(applyState);
        return Result.result(societyForMapper.updateById(societyFor));
    }

    @Override
    public Result examsEmail(Integer[] studentId, String text) {
        for (Integer stu : studentId) {
            sendMailAsync(stu, text);
        }
        UpdateSendSate(studentId);
        return Result.success(true);
    }

    @Override
    public void UpdateSendSate(Integer... studentId) {
        for (Integer id : studentId) {
            societyForMapper.UpdateState(id, 3);
        }

    }

    @Override
    public Result updateScore(int applyState, int computerExam, int interView, int penExam, int id, int studentId) {
        String textBody = "\n机试分数:" + computerExam + "" +
                "\n笔试分数:" + penExam + "" +
                "\n面试分数:" + interView;
        Integer[] studentid = {studentId};
        if (applyState == -1) {
            String text = "抱歉您的入社申请考试未通过!";
            examsEmail(studentid, text + textBody);
            int state = societyForMapper.updateApplyState(id, applyState);
            return Result.result(state);
        }
        String text = "恭喜您的入社申请考试已通过!";
        examsEmail(studentid, text + textBody);
        int score = societyForMapper.updateScore(applyState, computerExam, interView, penExam, id);
        return Result.result(score);
    }

    @Override
    public Result<List<SocietyFor>> Scoresearch(int deId,  String studentName, int page, int limit) {
        QueryWrapper<SocietyFor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deId", deId);
        queryWrapper.inSql("studentId", "select id from student where stuName like '%" + studentName + "%'");
        Page<SocietyFor> societyForPage = societyForMapper.selectPage(new Page<SocietyFor>(page, limit), queryWrapper);
        return Result.result(societyForPage);
    }

    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Override
    public Result passUser(int id, int userId, int deId, int studentId) {
        //1.发送短信通过成功待定

        //2.修改入社信息状态为5
        //3.修改用户deid
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionTemplate);
        try {
            int state = societyForMapper.updateApplyState(id, 5);
            state += userMapper.updateDeid(userId, deId);
            if (state != 2) {
                platformTransactionManager.rollback(transaction);
                Result.error(Error.System, "事务回滚");
            }
        } catch (TransactionException e) {
            platformTransactionManager.rollback(transaction);
            Result.error(Error.Other_E1R, "事务回滚" + e.getMessage());
        }
        platformTransactionManager.commit(transaction);
        sendMailAsync(studentId, "您的入社申请已通过，请等待管理人员通知！");
        return Result.success(true);
    }

    @Override
    public Result noPass(int id, int studentId) {
        int state = societyForMapper.updateApplyState(id, -1);
        if (state == 1) {
            sendMailAsync(studentId, "您在本次入社申请中失败了，请再接再厉吧！");
        }
        return Result.success(state);
    }

}
